class TreeBuilder:
    @classmethod
    def dictlist_to_tree(cls, res_list: list, id_key: str = 'id', parent_key: str = 'parent_id', children_key: str = 'children') -> list:
        """
        工具方法：根据列表信息生成树形嵌套数据
        :param res_list: 列表信息
        :param id_key: 列表中表示节点唯一标识的键名
        :param parent_key: 列表中表示父节点标识的键名
        :param children_key: 生成的树形结构中表示子节点的键名
        :return: 树形嵌套数据
        """
        # 检查输入数据
        if not res_list or not all(isinstance(item, dict) and id_key in item and parent_key in item for item in res_list):
            raise ValueError("列表信息格式不对,无法转化!")

        try:
            # 转成id为key的字典
            mapping: dict = {str(item[id_key]): item for item in res_list}

            # 树容器
            container: list = []

            for d in res_list:
                # 如果找不到父级项，则是根节点
                parent: dict = mapping.get(str(d[parent_key]))
                if parent is None:
                    container.append(d)
                else:
                    children: list = parent.get(children_key, [])
                    children.append(d)
                    parent[children_key] = children

            return container
        except KeyError as e:
            raise KeyError(f"Missing key in input data: {e}")
        except Exception as e:
            raise Exception(f"An error occurred while processing input data: {e}")
